import React, { useState, useEffect } from 'react';
import { Card, message } from 'antd';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

const { Meta } = Card;

const ItemTypes = {
    CARD: 'card'
};


// const imageUrls = [
//     'https://pic1.zhimg.com/v2-c661740055d91606880283692e40720c_r.jpg',
//     'https://wallpaperm.cmcm.com/4700eaf249b71d56d95aff8ca94313fa.jpg',
//     'https://pic3.zhimg.com/v2-5523ed93593ee4c7fd97b972d0af92d3_r.jpg',
//     'https://pic1.zhimg.com/v2-3e2fe005af51c7636486d2a9a99cfb3e_r.jpg',
//     // ... 更多图片链接
// ];

// const getRandomImageUrl = () => {
//     const randomIndex = Math.floor(Math.random() * imageUrls.length);
//     return imageUrls[randomIndex];
// };

// *   `DndProvider`, `useDrag`, `useDrop`: `react-dnd` 库提供的 Hook，用于实现拖放功能。
// *   `HTML5Backend`:  `react-dnd` 的 HTML5 后端，使用 HTML5 拖放 API。
// `card` (卡片数据) 和 `onDrop` (拖放处理函数
const DraggableCard = ({ card, onDrop }) => {
    const [{ isDragging }, drag] = useDrag(() => ({
        type: ItemTypes.CARD,
        item: { id: card.id },
        collect: (monitor) => ({//收集拖动状态，这里收集 `isDragging` 状态。
            isDragging: !!monitor.isDragging(),
        }),
    }), [card]);

    const [{ isOver }, drop] = useDrop(() => ({
        accept: ItemTypes.CARD,
        drop: (item) => onDrop(item.id, card.id),
        collect: (monitor) => ({
            isOver: !!monitor.isOver(),
        }),
    }), [card]);

    return (
        <div ref={drop} style={{ opacity: isDragging ? 0.5 : 1, margin: 16 }}>
            <div ref={drag}>
                <Card
                    hoverable
                    style={{
                        width: 240,
                        border: isOver ? '2px solid green' : '1px solid #f0f0f0',
                    }}
                    cover={<img alt="example" src={card.image_url} />}

                >
                    <Meta
                        title={card.name}
                        description={
                            <div>
                                <p>稀有等级: {card.rarity}</p>
                                <p>攻击力: {card.attack}</p>
                                <p>防御力: {card.defense}</p>
                                <p>生命力: {card.health}</p>
                            </div>
                        }
                    />
                </Card>
            </div>
        </div>
    );
};

const WeiYang = () => {
    const { userId } = useParams();

    const [cards, setCards] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const fetchCards = async () => {
        setLoading(true);
        try {
            const response = await axios.post('http://localhost:3001/getUserCards', { userId: userId });
            const data = await response.data;
            setCards(data);
        } catch (error) {
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCards();
    }, [userId]);

    const handleFeed = async (feederCardId, targetCardId) => {
        try {
            const response = await axios.post('http://localhost:3001/feedCard', {
                userId: userId,
                feederCardId: feederCardId,
                targetCardId: targetCardId
            });
            message.success('喂养成功');
            // 重新获取卡片列表，刷新展示
            fetchCards();
        } catch (error) {
            message.error('喂养失败：' + error.message);
        }
    };

    if (loading) {
        return <p>Loading...</p>;
    }

    if (error) {
        return <p>Error: {error}</p>;
    }

    return (
        <DndProvider backend={HTML5Backend}>
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                {cards.map((card) => (
                    <DraggableCard key={card.id} card={card} onDrop={handleFeed} />
                ))}
            </div>
        </DndProvider>
        // -   使用 `DndProvider` 包裹整个页面，启用拖放功能。
        // -   遍历 `cards` 数组，渲染每个卡片为 `DraggableCard` 组件。
        // -   将 `handleFeed` 函数传递给 `DraggableCard`，用于处理卡片拖放事件。

    );
};

export default WeiYang;
